<?PHP
/**
 * @author Rick Overman
 * @version $Id$
 * @copyright Push Button Labs,  9 September, 2008
 * @package default
 **/

/**
 * Define DocBlock
 **/

require_once(TEMPLATEPATH.'/op/layout.OP.php');
/**
 * OP (OnePress) Theme controller class 
 * 
 * @package default
 * @author Rick Overman
 **/
 
class OP {

	var $layout;
	var $feature_registry;

	function OP() {
		$this->feature_registry = new OP_Feature();
		$this->layout =& new OP_Layout();
		
		OP::add_widgets();
				
		if (is_admin()){
			if(strpos($_SERVER['REQUEST_URI'],'themes.php?activated=true')) OP::install(); // Theme is being installed
			
			add_action('admin_notices',array('OP','admin_notices'));
			
			if(strpos($_SERVER['REQUEST_URI'],'widgets.php')) // copy / paste for sidebar widgets
				add_action('admin_notices',array('OP','sidebar_editing_options'));
			
			if ($modules = get_option('op_modules')){
				// Module specific nav
				if($modules['phpBB'] == 1){
					add_action('publish_page', array('OP','update_settings'),9,2);
					add_action('delete_post', array('OP','update_settings'),9,2);
				}
			}
			
			add_action('init',array('OP','admin_head'));
			add_action('admin_head',array('OP','admin_init'));
			
			add_action('wp_insert_post', array('OP_ImageSelection','do_post'));
			add_action('save_post', array('OP_ImageSelection','do_post'));
			
			// OnePress Admin Dashboard Widget
			add_action('wp_dashboard_setup', array('OP','register_dashboard_widget'));
			add_filter('wp_dashboard_widgets', array('OP','add_dashboard_widget'));
			
			if ($modules = get_option('op_modules')){
				// Module specific nav
				if($modules['phpBB'] == 1){
					add_action('admin_action_update',array('OP','update_settings'));
					add_action('switch_theme',array('OP','update_settings'));
				}
			}
		}
		
		global $pagenow;
		if(!is_admin() || $pagenow == 'profile.php'){
			// set priority 9 so they load before the rest of the sidebar styles and scripts
			add_action('wp_print_styles', array($this,'add_scripts'),9);

			// in order be be able to override the CSS the child stylesheet needs to load last
			add_action('wp_print_styles', array($this,'add_child_styles'),10);
			
			// As of 2.6.1 wp_print_styles is not called by default so we add it here
			// set order 5, CSS needs to be emitted before Javascript
			add_action('wp_head','wp_print_styles',5);
			
			// For security remove the WP Genertor which reports the WP Version Number
			remove_action('wp_head', 'wp_generator');
		}
	}
	
	function admin_notices(){
		$user = wp_get_current_user();
		$key =  'op_clipboard_admin_notices-'.$user->ID;
		
		if($notice = get_option($key)){
			echo $notice;
			delete_option($key);
		}
	}
	
	function admin_head(){
		$url = get_bloginfo('template_directory').'/op/admin/';
		if(strpos($_SERVER['REQUEST_URI'],'post.php') || strpos($_SERVER['REQUEST_URI'],'post-new.php')){
			wp_register_script('oppostjs', $url.'scripts/post.js',array('jquery'));
			wp_enqueue_script('oppostjs');
			wp_register_style('oppostcss',$url.'styles/post.css');
			wp_enqueue_style('oppostcss');
		}

		wp_deregister_script('admin-widgets'); // remove default WordPress widget JS code
		wp_register_script('opwidgetsadminjs', $url.'scripts/widgets_admin.js',array('jquery','jquery-ui-sortable','interface'));
		wp_localize_script('opwidgetsadminjs','widgetsL10n', array( // localize our js file so WP widget js is easier to copy/paste
			'add' => __('Add'),
			'edit' => __('Edit'),
			'cancel' => __('Cancel'),
			'lameReminder' => __('Remember to click the "Save Changes" button at the bottom of the Current Widgets column after you\'re all done!'),
			'lamerReminder' => __("You're about to leave without having saved your changes!")
		));
		wp_enqueue_script('opwidgetsadminjs');
	}
	
	function admin_init(){
		// Add meta box for Image Management within writing a post
		add_meta_box('opimagemanage', __('Image Selection'), array('OP_ImageSelection','do_render'), 'post', 'normal', 'high');
	}

	function register_dashboard_widget() {
		wp_register_sidebar_widget('dashboard_op', __('OnePress Updates', 'op'), array('OP','dashboard_op'),
			array(
				'all_link' => 'http://www.onepresscommunity.com',
				'feed_link' => 'http://feeds.feedburner.com/onepressdashboard',
				'width' => 'half'
			)
		);
	}

	function add_dashboard_widget($widgets) {
		global $wp_registered_widgets;
		if (!isset($wp_registered_widgets['dashboard_op'])) {
			return $widgets;
		}
		
		array_splice($widgets, sizeof($widgets)-1, 0, 'dashboard_op');
		return $widgets;
	}
	 
	function dashboard_op(){
		echo $before_widget;
		echo $before_title;
		echo $widget_name;
		echo $after_title;
		
		include_once(ABSPATH . WPINC . '/rss.php');
		$rss = @fetch_rss('http://feeds.feedburner.com/onepressdashboard');
		wp_widget_rss_output($rss, array(
				'items' => 2,
				'show_summary' => 1,
				'show_author' => 0,
				'show_date' => 1)
			);
	
		echo $after_widget;
	}
	
	function install() {
		global $wp_registered_widgets,$wp_registered_sidebars;
		
		$sidebar_widgets = wp_get_sidebars_widgets();
		
		// Add initial widgets when activating theme
		$new_widgets = array();

		if(count($sidebar_widgets['default-main']) == 0){
			$updating = TRUE;
			// Add feature carousel widget
			$id = OP::get_next_widget_id();
			$new_widgets[] = 'feature_carousel-'.$id;
			$stored_options = get_option('widget_op_feature_carousel');
			$stored_options[$id] = array('title'=>'','tag'=>'','style'=>'default');
			update_option('widget_op_feature_carousel', $stored_options);
			
			// Add default content widget
			$id = OP::get_next_widget_id();
			$new_widgets[] = 'content_body-'.$id;
			$stored_options = get_option('widget_op_content_body');
			$stored_options[$id] = 	array(
				'content_layout'	=> array('title','date','post-body','tags','div','categories','edit-link','comments'),
				'advanced'			=> array(
					'author_pre'		=> 	'by ',
					'time_pre'			=> 	'at ',
					'time_format'		=> 	'',
					'date_format'		=> 	'F j, Y',
					'more_link'			=>	 'Read the rest of this entry &raquo;',
					'tag_label'			=> 	'Tags: ',
					'tag_before'		=> 	'',
					'tag_separator'		=>	', ',
					'tag_after'			=>	'',
					'category_label'	=>	'Categories: ',
					'category_separator'	=>	', ',
					'category_parents'		=> 	'',
					'comment_link_none'		=> 	'No Comments &#187;',
					'comment_link_one'		=>	'1 Comment &#187;',
					'comment_link_multiple'	=>	'% Comments &#187;'
			));
			update_option('widget_op_content_body', $stored_options);
			
			$sidebar_widgets['default-main'] = $new_widgets;
			wp_set_sidebars_widgets($sidebar_widgets);
		}
		
		if(!get_option('op_layout'))
			add_option('op_layout',array('default'=>array('main','sidebar1'),'footer'=>array('column1','column2','column3')));

	}
	
	function get_next_widget_id(){
		static $i = 0;
		return (time() - 199145600).$i++;
	}
	
	function add_child_styles() {
		wp_register_style( 'styles', get_bloginfo('stylesheet_url') );
		wp_enqueue_style('styles');
	}
	
	function add_scripts() {
		$url = get_bloginfo('template_directory');
				
		wp_register_script('onepressjs', $url.'/scripts/op.js');
		wp_enqueue_script('onepressjs');

		if(has_action('op_navigation','op_navigation')){ // check to make sure nav hook exists first
			wp_register_script('opnav', $url.'/scripts/nav.js', array('onepressjs'));
			wp_enqueue_script('opnav');
		}
		
		if(function_exists('wp_list_comments') && is_singular() ) wp_enqueue_script( 'comment-reply' ); // support for 2.7 comments
	}
	
	/**
	 * add_widgets
	 *
	 * Autoload all widget files located in /lib/widgets
	 *
	 * @return void
	 **/
	function add_widgets(){
		require_once(TEMPLATEPATH.'/op/widget.OP.php');
	    foreach (glob(TEMPLATEPATH.'/widgets/widget.*.php') as $file) {
	        include $file;
	    }
	}
	
	function update_settings(){
		$user = wp_get_current_user();
		$key =  'op_clipboard_admin_notices-'.$user->ID;
		
		$output = OP::cache_settings();
		if(strlen($output) > 0 && !get_option($key)){
			add_option($key,$output);
		}
	}
	
	/**
	 * 
	 * cache_settings
	 * 
	 * required if phpBB module is active
	 *
	 * @return void
	 **/
	function cache_settings($page_id=NULL) {
		if($page_id != NULL){ // check to see if submitted item is a page
			global $wpdb;
			$result = $wpdb->get_results('SELECT post_type FROM '.$wpdb->posts.' WHERE ID="'.$page_id.'"');
			if($result[0]->post_type != 'page') // if submitted item is a post, return
				return;
		}
		
		$home = get_settings('home');

		ob_start();
		//
		// If user overrides op_navigation action, they are doing something custom for their navigation
		// Do same custom navigation for the flat file, call hook instead of default
		//
		if(has_action('op_navigation','op_navigation')){
			OP::default_nav();
		}
		else{
			do_action('op_navigation');
		}

		$new_nav = ob_get_clean();
		
		$new_title = get_bloginfo('name');
		$new_description = get_bloginfo('description');
		preg_match('/\/(\w+)$/',STYLESHEETPATH,$matches);
		$new_theme = $matches[1];
		
		// Get user defined image
		$new_img = '';
		if (($current_img = get_option('op_theme_header_img')) && $current_img != 0){
			if($files = wp_get_attachment_image_src($current_img, 'full')){
				$new_img = $files[0];
			}
		}
		
		$options_output = <<<EOS
<?PHP
	\$op_navigation = <<<EOT
$new_nav
EOT;
	\$op_title = <<<EOT
$new_title
EOT;
	\$op_description = <<<EOT
$new_description
EOT;
	
	\$op_header_image = <<<EOT
$new_img
EOT;
	
	\$op_current_theme = <<<EOT
$new_theme
EOT;

EOS;

		$file_path = dirname(dirname(__FILE__)).'/';
		if((!file_exists($file_path.'settings.inc.php') && is_writable($file_path)) || is_writable($file_path.'settings.inc.php')){
			$res = fopen($file_path.'settings.inc.php','w+b');
			fwrite($res,$options_output);
			fclose($res);
		}
		else{
			$output = '<div class="updated">';
			if(strlen($post->post_title) > 0)
				$output .= '<h1>Save successful</h1>';
				
			$output .= '<p><strong>Your site options needs to be updated</strong></p>';
			$output .= '<p>If your <code>'.$nav_file_path.'settings.inc.php</code> file were <a href="http://codex.wordpress.org/Changing_File_Permissions">writable</a>, we could do this automatically, but it isn&#8217;t so this is the new options code you should have in your <code>'.$file_path.'settings.inc.php</code> file. Click in the field and press <kbd>CTRL + a</kbd> to select all.</p>';
			$output .= '<p><textarea rows="5" style="width: 98%;" name="rules" id="rules">'. wp_specialchars($options_output) .'</textarea></p>';
			
			if(strlen($post->post_title) > 0)
				$output .= '<p><a href="/wp-admin/page.php?action=edit&post='. $id .'">Return to "'. $post->post_title .'"</a></p>';
			
			$output .= '</div>';
			
			return $output;
		}
	}
	
	function default_nav(){
		echo <<<EOS
<div id="op_navigation">
<div id="op_navigation2">
	<ul>
EOS;
		// query for wp_list_pages
		$page_query = 'title_li=&depth=3&sort_column=menu_order&hierarchical=1';
		
		if(get_option('show_on_front') == 'page'){ // if using a static page for front page display
			$home_id = get_option('page_on_front'); // get page id of homepage
			$page_query .= '&exclude='.$home_id; //exclude homepage from query
		}
		$home = get_settings('home'); // home link
		echo '<li><a href="'.$home.'">Home</a></li>';
		
		if ($modules = get_option('op_modules')){
			
			// Module specific nav
			if($modules['phpBB'] == 1){
				if(!$path = get_option('op_module_phpbb'))
					$path = 'forum/';
				if(!$tab = get_option('op_module_phpbb_tab'))
					$tab = 'Community';
				$path = get_option('siteurl').'/'.$path; // append forum path to siteurl
				echo <<<EOS
		<li><a href='$path'>$tab</a></li>
EOS;
			}
		}
	
		wp_list_pages($page_query); // get and echo pages
		
		echo <<<EOS
	</ul>
	<!-- OnePress - Do not remove --><span class="forclear"></span><!-- OnePress - Do not remove -->
</div>
</div>
EOS;
	}
	
	/**
	 * copy / paste for sidebar widgets
	 */
	function sidebar_editing_options(){
		// If using static page for front page, notify them to use Home here.
		if(get_option('show_on_front') == 'page'){
			echo '<p><i><b>Attention: </b>A static page is currently set to display as the front page for your site.  To edit widgets for the front page, choose "Page" followed by the name of the page. To customize the posts page, edit "Home" rather than the individual page in order for changes to be effective.</i></p>';
		}
		echo <<<EOS

		<div id="store_data"></div>
		<style type="text/css">.button-secondary[disabled]{ color: #ccc;}</style>
		<div style="float:right; margin-right: 20px; z-index:200">
			<input class="button-secondary" id="copy_sidebar_trigger" type="submit" value="Copy Current Sidebar"/>
			<input class="button-secondary" id="paste_sidebar_trigger" type="submit" value="Paste Sidebar" disabled/>
EOS;
 		echo '<input type="hidden" id="op_clipboard_nonce" value="'.wp_create_nonce('op-clipboard_sidebar_method').'">';
		echo '</div>';

		echo '<div style="clear:right"></div>';
	}
	
	function render() {
		$this->layout->render();
	}
	
	function render_footer(){
		echo $this->layout->render_footer();
	}	
}

/**
 * undocumented class
 *
 * @package default
 * @author Sean
 **/
class OP_Feature{
	var $registered;
	function OP_Feature(){
		$this->registered = array();
	}
	
	// Public
	function register($id){
		if(in_array($id,$this->registered)){
			return false;
		}
		else{
			$this->registered[] = $id;
			return true;
		}
	}
	
	// Public
	// Pass in array of features
	function get_available($features){
		global $post;
		$toremove = array();
		$count = 0;
		for($i = 0; $i < count($features); $i++){
			if ( (is_single() && $features[$i]->ID == $post->ID) // If is_single and the current post.
				|| !$this->register($features[$i]->ID) // If is registered in features registry
			){
				$toremove[$i] = TRUE;
			}
			else{
				$count++;
				if($count == 4) break;
			}
		}
		$features = array_diff_key($features,$toremove);
		$features = array_merge(array(),$features);
		return $features;
	}
}

/**
 * op_style_tag_cloud
 *
 * @param  string tag html string from wp_tag_cloud action hook
 * @return string transformed html string which can be styled with CSS
 **/
function op_style_tag_cloud($tags)
{
	$tags = preg_replace_callback("|(class='tag-link-[0-9]+)('.*?)(style='font-size: )([0-9]+)(pt;')|",
		create_function(
			'$match',
			'$low=1; $high=5; $sz=($match[4]-8.0)/(22-8)*($high-$low)+$low; return "{$match[1]} tagsz-{$sz}{$match[2]}";'
		),
		$tags);
	return $tags;
}

class OP_ImageSelection{
	
	function get_image($post_id,$size='thumbnail',$default = TRUE){
		// Check custom fields for image
		if($img = get_post_meta($post_id, 'op_img_'.$size,TRUE)){
			$wp_size = $size == 'feature' ? 'large' : $size;
			if(is_numeric($img) && $files = wp_get_attachment_image_src($img, $wp_size)){ // Image is an attachment
				$img = $files[0];
			}
			else{ // Image is a url
				// If image is a flickr embed.  We can pull the correct size from flickr.
				// if(preg_match('/farm[0-9]+.static.flickr.com/',$img)){ // If Flickr, use _m size
				// 	$flickr_size = $size == 'feature' ? '_b' : '_m';
				// 	$img = preg_replace('/(http:\/\/[a-z0-9\-\.\/_]+)([\_]*[a-z]{1}+)(\.[jpg]{3,4})/i','$1'.$flickr_size.'$3',$img);
				// 	// TODO -- somehow need to backlink to flickr
				// }
			}
		}
		else if($default == TRUE){	// show default image
			// Get path to possible default image in child theme.  If it exists, use that instead of OnePress defaults
			if(file_exists(STYLESHEETPATH.'/images/default_'.$size.'.png')){
				$img = get_bloginfo('stylesheet_directory').'/images/default_'.$size.'.png';
			}
			else{  // use OnePress default
				$img = get_bloginfo('template_directory').'/images/default_'.$size.'.png';
			}
		}
		else{
			$img = '';
		}
		
		return $img;
	}
	
	function do_render(){
		global $post;
		echo '<div id="op_img_wrap">'.OP_ImageSelection::render($post->ID).'</div>';
	}
	
	function render($post_id = 0){
		$output = '<div style="float:right"><a href="http://onepresscommunity.com/docs/onepress/#admin-image_management">Help</a></div>';
		if($post_id != 0 && $children = get_children(array('post_parent'=>$post_id,'post_type'=>'attachment'))){ // Check for attached imaged
			$output .= "<p>Choose image to use for image type: <select id='op_img_type'>";
			$output .= '<option value="thumbnail">Thumbnail</option>';
			$output .= '<option value="featurette">Featurette</option>';
			$output .= '<option value="feature">Feature</option>';
			$output .= '</select>';
			
			$output .= '</p>';
			$output .= "<p>Select one of the following images:</p>";
			$default_img = get_bloginfo('template_directory').'/op/admin/images/clear_image.png';
			$output .= '<div class="op_image_selection_img" id="op_img-0"><img src="'.$default_img.'" class="selected"/></div>';
			
			foreach($children as $child){
				if($files = wp_get_attachment_image_src($child->ID)){
					$output .= '<div class="op_image_selection_img" id="op_img-'.$child->ID.'"><img src="'.$files[0].'" /></div>';
				}
			}
			$types = array('thumbnail','featurette','feature');
			foreach($types as $type){
				$value = get_post_meta($post_id, 'op_img_'.$type,true);
				$output .= '<input type="hidden" id="op_img_'.$type.'" name="op_img_'.$type.'" value="'.$value.'">';
			}
			$output .= '<input type="hidden" name="op_img_noncename" id="op_img_noncename" value="';
			$output .= wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

		}
		else{
			$output .= '<p>Use the WordPress Media Library ["Add Media" &raquo; "Add an Image"] to add images to this post</p>';
		}

		return $output;
	}
	
	function do_post($post_id){
		if ( !wp_verify_nonce( $_POST['op_img_noncename'], plugin_basename(__FILE__) )) {
			return $post_id;
		}
		$types = array('thumbnail','featurette','feature');
		foreach($types as $type){
			if(get_post_meta($_POST['post_ID'], 'op_img_'.$type)){
				update_post_meta($_POST['post_ID'],'op_img_'.$type,$_POST['op_img_'.$type]);
			}
			else{
				add_post_meta($_POST['post_ID'],'op_img_'.$type,$_POST['op_img_'.$type],TRUE);
			}
		}
	}
	
	function get_images(){
		echo OP_ImageSelection::render($_POST['post_id']);
	}
}


class OP_Modules{
	function upgrade($module=NULL){
		if($module == NULL) $module = $_POST['module'];
		
		$load_module = strtolower($module);
		// Load module files
		if(file_exists(TEMPLATEPATH.'/op/modules/module.'.$load_module.'.php')){
			require_once(TEMPLATEPATH.'/op/modules/module.'.$load_module.'.php');
		}
		
		// If module class has an install method, call it
		if(is_callable(array('module_'.$load_module,'upgrade'))){
			$response = call_user_func(array('module_'.$load_module,'upgrade'));
			if($response['error'] == 0){
				$updatemodules[$module] = 1; // module can be activated
			}
		}
	}
}

add_action('wp_tag_cloud', 'op_style_tag_cloud');

?>